/**
 *   FUSE-J: Java bindings for FUSE (Filesystem in Userspace by Miklos Szeredi (mszeredi@inf.bme.hu))
 *
 *   Copyright (C) 2003 Peter Levart (peter@select-tech.si)
 *
 *   This program can be distributed under the terms of the GNU LGPL.
 *   See the file COPYING.LIB
 */

package fuse.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;


public class Log
{
   public static final int DEBUG = 0;
   public static final int INFO = 1;
   public static final int WARN = 2;
   public static final int ERROR = 3;

   public static final int level;

   private static final String[] levelStrings = new String[]{"DEBUG", "INFO", "WARN", "ERROR"};
   private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

   static
   {
      String levelString = System.getProperty("fuse.log");
      int defaultLevel = INFO;

      if (levelString != null)
      {
         for (int i = 0; i < levelStrings.length; i++)
         {
            if (levelString.equals(levelStrings[i]))
            {
               defaultLevel = i;
               break;
            }
         }

      }

      level = defaultLevel;
   }


   private String topic;


   public Log(Class clazz)
   {
      this(clazz.getName());
   }

   public Log(String topic)
   {
      this.topic = topic;
   }


   public void debug(String msg)
   {
      _log(DEBUG, msg);
   }

   public void info(String msg)
   {
      _log(INFO, msg);
   }

   public void warn(String msg)
   {
      _log(WARN, msg);
   }

   public void error(String msg)
   {
      _log(ERROR, msg);
   }

   public void log(int level, String msg)
   {
      _log(level, msg);
   }


   private void _log(int level, String msg)
   {
      if (level >= this.level)
      {
         String date;

         synchronized (dateFormat)
         {
            date = dateFormat.format(new Date());
         }

         StackTraceElement ste = new Throwable().getStackTrace()[2];
         System.err.println(
            date +
            " [" + levelStrings[level] + "] " +
            Thread.currentThread().getName() +
            " <" + ste.getClassName() + "." + ste.getMethodName() + "> " +
            msg
         );
      }
   }
}
